import wx from 'weixin-js-sdk'
import axios from 'axios'
import $ from 'jquery'

function isWeiXin() {
    var ua = window.navigator.userAgent.toLowerCase()
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        return true;
    } else {
        return false;
    }
}

// var init = function(type){
//   return new Promise(function(resolve, reject) {
//     // if(!isWeiXin()) {
//     //   return;
//     // }
//     // todo: 获取config的接口地址
    // axios.post('/api/promote/wxShareConfig',{
    //   url: location.href.split('#')[0],
    //   type: type
    // }).then(function(data) {
    //   var wxOptions = $.extend({},data,{
    //     debug: false,
    //     jsApiList: [
    //       'updateAppMessageShareData',
    //       'updateTimelineShareData',
    //       'onMenuShareWeibo'
    //     ]
    //   })
    //   wx.config(wxOptions);
    // })

//     wx.ready(function() {
//       resolve()
//     })

//     wx.error(function(res) {
//       reject(res)
//     })

//   })
// }
var init = function(type) {
    return axios.post('/promote/wxShareConfig',{
      url: location.href.split('#')[0],
      type: type
    }).then(function(data) {
      wx.ready(function(){
      var wxOptions = $.extend({},data,{
        debug: false,
        jsApiList: ["onMenuShareTimeline",
                "onMenuShareAppMessage",
                "onMenuShareQQ",
                "onMenuShareWeibo",
                "onMenuShareQZone"
        ]
      })
      wx.config(wxOptions);
      })
    })
}


/**设置在微信中分享时候的信息
 * @param {Object} shareInfo - 设置分享信息的参数对象
 * @param {String} shareInfo.title - 标题
 * @param {String} shareInfo.desc - 描述
 * @param {String} shareInfo.imgUrl - 图标的地址
 * @param {Number} type - 类型 1 分享 2 邀请
 * @param {String} url - 分享地址
 */
var setShareInfo = function (shareInfo, url = location.href, type = 1, isDebugging = false) {
    console.log('setShareInfo')
    init(type).then(function () {
        console.log("init-then")
        var realShareInfo = $.extend({}, {
            link: url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        }, shareInfo);

                wx.onMenuShareTimeline(realShareInfo);
        wx.onMenuShareAppMessage(realShareInfo);
        wx.onMenuShareQQ(realShareInfo);
        wx.onMenuShareWeibo(realShareInfo);
        wx.onMenuShareQZone(realShareInfo);
        // wx.updateAppMessageShareData(realShareInfo);
        // wx.updateTimelineShareData(realShareInfo);
        // wx.onMenuShareWeibo(realShareInfo);
    }).catch(function (err) {
      console.log(err)
        if (isDebugging) {
            alert(JSON.stringify(err));
        }
    });
}

export default setShareInfo;